/*
 * 文件名：UserAction.java
 * 版权：Copyright by www.wootide.com
 * 描述：用户的Action层类
 * 修改人：lizl
 * 修改时间：2012-9-13
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */
package com.wootide.cms.manager.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.wootide.cms.common.manager.BeanFactory;
import com.wootide.cms.common.manager.Constants;
import com.wootide.cms.common.manager.GeneralUtils;
import com.wootide.cms.common.manager.PageEntity;
import com.wootide.cms.common.manager.SHException;
import com.wootide.cms.manager.pojo.User;
import com.wootide.cms.manager.service.IUserService;

/**
 * 〈一句话功能简述〉:用户Action层的请求控制转发、异常处理等<br>
 * 〈功能详细描述〉<br>
 * 在Action层其核心功能：<br>
 *     *请求控制转发；<br>
 *     *对底层异常的捕获，并且做出相应处理；<br>
 *     *安全控制；<br>
 * @author lizl
 * @version 2012-9-13
 * @see ManagerAction
 * @since
 */

public class ManagerAction extends BaseAction
{
    
    /**
     * 意义，目的和功能，以及被用到的地方<br>
     */
    private static final long serialVersionUID = 8702435927541092957L;
    
    /**
     * 根据业务需求，对某些操作或是异常处理，进行日志记录；
     */
    private static final Logger LOGGER = Logger.getLogger(ManagerAction.class);
    
    /**
     * 业务层接口:userService/roleOperaService/roleService
     */
    public IUserService userService;
    
    //public IRoleOperaService roleOperaService;
    
    //public IRoleService roleService;
    
    /**
     * user:前端表达数据的封装对象；
     */
    public User user;
    
    /**
     * 查询条件及其值
     */
    private String searchName;
    
    private String searchValue;
    
    /**
     * userList:查询返回对象记录集合；
     */
    public List<User> userList;
    
    /**
     * userIds:在进行多用操作时（例如，授权、启用、停用）进行封装
     */
    public String userIds = "";
    
    /**
     * roleNameS:在授权时（对多用户进行多角色授权）
     */
    //public String roleNameS = "";
    /**
     * roleList:角色集合
     */
    //public List<Role> roleList;
    /**
     * Description: 初始化userService业务类接口<br>
     * Implement: <br>
     * @throws SHException
     * @see
     * @return void
     * @author lizl
     */
    private void initService() throws SHException
    {
        try
        {
            if (GeneralUtils.isNull(userService))
            {
                userService = (IUserService)BeanFactory.getBean("userService");
                //roleOperaService = (IRoleOperaService)BeanFactory.getBean("roleOperaService");
                //roleService = (IRoleService)BeanFactory.getBean("roleService");
            }
        }
        catch (Exception e)
        {
            // LOGGER.error("初始化业务类失败！");
            throw new SHException("初始化业务类失败！");
        }
    }
    
    /**
     * Description: 用户管理界面;<br>
     *              查询;<br>
     * Implement: <br>
     * @return
     * @see
     * @return String
     * @author lizl
     */
    public String doQuery()
    {
        if (GeneralUtils.isNull(user))
        {
            user = new User();
        }
        try
        {
            user = initSearch(user,searchName,searchValue);
            initService();
            //每一页的起始位置
            int start = PageEntity.getBeginIndex(Integer.parseInt(pageIndex),
                    Constants.PAGE_SIZE);
            //总记录数
            int count = userService.getUserCount(user);
            //某一页的记录集合
            userList = userService.getUserList(user, start, Constants.PAGE_SIZE);
            if (userList == null)
            {
                userList = new ArrayList<User>();
            }
            //封装的分页查询结果集合
            page = new PageEntity(userList, count, Constants.PAGE_SIZE,
                    Integer.parseInt(pageIndex));
            
            //--------开始-----------------
            //获取/charts的绝对路径
            
            //--------结束-----------------
            user.setUserName("用户姓名");
        }
        catch (SHException e)
        {
            // LOGGER.error(e.getMessage());
        }
        return SUCCESS;
    }
    
    /**
     * Description: 跳转到用户增加页面<br>
     * Implement: <br>
     * @return
     * @see
     * @return String
     * @author lizl
     */
    public String toAddUser()
    {
        try
        {
            initService();
        }
        catch (SHException e)
        {
            LOGGER.error(e.getMessage());
        }
        return "toAdd";
    }
    
    /**
     * Description: 在Action层的增加用户操作<br>
     * Implement: 调用Service层的addUser()方法<br>
     *            【注】命名：toXXXUser,(XXX表示：add/del/get/mod/grant/start/stop)<br>
     * @return：在strutsXXX.xml文件中控制转发到相应的页面：<br>
     *          参数默认有：success/error/input/...
     * @see
     * @return String
     * @author lizl
     */
    public String addUser()
    {
        try
        {
            initService();
            
            //初始化密码为：123456;用户第一次登陆成功后需要修改密码。
            user.setUserPwd("123456");
            userService.addUser(user);
            
        }
        catch (SHException e)
        {
            //  LOGGER.error(e.getMessage());
        }
        /*catch (UnsupportedEncodingException e)
        {
            LOGGER.error("出现字符乱码！");
        }*/
        return SUCCESS;
    }
    
    /**
     * Description: 通过ID查看当前用户信息<br>
     * Implement: <br>
     * @return
     * @see
     * @return String
     * @author lizl
     */
    public String detailUser()
    {
        try
        {
            initService();
            user = userService.getUserById(user);
        }
        catch (SHException e)
        {
            LOGGER.error(e.getMessage());
        }
        return SUCCESS;
    }
    
    /**
     * Description: 跳转到用户修改页面<br>
     * Implement: <br>
     * @return
     * @see
     * @return String
     * @author lizl
     */
    public String toModUser()
    {
        try
        {
            initService();
            user = userService.getUserById(user);
            
            //将当前需要修改用户的角色信息，临时存放在request中；
            /*this.getRequest().getSession().setAttribute("userRoles",
                    user.getUserRoles());*/
        }
        catch (SHException e)
        {
            //  LOGGER.error(e.getMessage());
        }
        return "toMod";
    }
    
    /**
     * Description: 修改用户信息<br>
     * Implement: <br>
     * @return
     * @see
     * @return String
     * @author lizl
     */
    public String modUser()
    {
        try
        {
            initService();
            
            /*
             * 在form表单中的user的属性userRoles是为null，直接执行以后，就会因为userRoles=null
             * 导致hibernate在执行完update语句后，还会执行一条delete语句——删除与该用户相关的所有
             * 角色信息，即将该用户的角色关联信息设置为null;
             */
            /*Set<Role> userRoles = (Set<Role>)this.getRequest()
                    .getSession()
                    .getAttribute("userRoles");
            user.setUserRoles(userRoles);*/

            userService.modUser(user);
        }
        catch (SHException e)
        {
            //  LOGGER.error(e.getMessage());
        }
        
        return SUCCESS;
    }
    
    public String toGrantUser()
    {
        try
        {
            initService();
            
            //改：在授权页面，进行异步获取
            this.userList = this.getObjListByIdS(this.getUserIds());
            
            //获取所有角色信息
            //this.roleList = roleService.getAllRoles();
            
        }
        catch (Exception e)//SHException
        {
            //  LOGGER.error("跳转到授权页面失败！");
        }
        return TO_GRANT;
    }
    
    /**
     * Description: 1.对用户进行授权；<br>
     *              2.对“授权”操作进行日志记录；<br>
     * Implement: <br>
     * @return
     * @see
     * @return String
     * @author lizl
     */
    /*public String grantUser()
    {
        try
        {
            initService();
            //Role roleTemp = null;
            
            //字符乱码:从user_grant.jsp-->userAction
            String temp = changeToUTF8(roleNameS);
            
            *//**
                     * 在授权时，使用到的角色信息；
                     * 这里使用分隔符“,”；
                     */
    /*
                String[] roleNameSTemp = temp.split(",");
                
                List<User> userListTemp = getObjListByIdS(userIds);
                *//**
                     * 对多用户进行多角色授权
                     */
    /*
                for (User userTemp : userListTemp)
                {
                    userTemp.getUserRoles().clear();
                    for (String roleName : roleNameSTemp)
                    {
                        //roleTemp:应该是通过roleName到数据中加载出来
                        roleTemp = new Role();
                        roleTemp.setRoleName(roleName);
                        
                        //根据属性查询相应的单个对象
                        roleTemp = roleService.getRole(roleTemp);
                        
                        //对未授权用户，建立关联关系
                        userTemp.getUserRoles().add(roleTemp);
                    }
                    userService.grantUser(userTemp, roleTemp);
                }
            }
            catch (SHException e)
            {
                LOGGER.error(e.getMessage());
            }
            catch (UnsupportedEncodingException e)
            {
                LOGGER.error("不支持该字符类型！");
            }
            return SUCCESS;
        }*/

    /**
     * Description: 1.启用某个用户；<br>
     *              2.对“启用”操作进行日志记录；<br>
     *              [注]用户状态：1代表停用，0启用，2删除，默认启用；非空
     * Implement: <br>
     * @return
     * @see
     * @return String
     * @author lizl
     */
    public String startUser()
    {
        try
        {
            initService();
            String[] userIds = this.getUserIds().split(",");
            User userTemp = null;
            for (String userID : userIds)
            {
                userTemp = new User();
                userTemp.setUserId(Long.valueOf(userID));
                user = userService.getUserById(userTemp);
                
                //启用
                user.setUserState(0);
                userService.startUser(user);
            }
        }
        catch (SHException e)
        {
            //  LOGGER.error(e.getMessage());
        }
        return SUCCESS;
    }
    
    /**
     * Description: 1.停用某个用户；<br>
     *              2.对“停用”操作进行日志记录；<br>
     * Implement: <br>
     * @return
     * @see
     * @return String
     * @author lizl
     */
    public String stopUser()
    {
        try
        {
            initService();
            String[] userIds = this.getUserIds().split(",");
            User userTemp = null;
            for (String userID : userIds)
            {
                userTemp = new User();
                userTemp.setUserId(Long.valueOf(userID));
                user = userService.getUserById(userTemp);
                
                //停用
                user.setUserState(1);
                userService.startUser(user);
            }
        }
        catch (SHException e)
        {
            //  LOGGER.error(e.getMessage());
        }
        return SUCCESS;
    }
    
    /**
     * 公共方法
     * Description: 通过在UI层选取的对象的ID集合，获取到相应的对象集合<br>
     * Implement: <br>
     * @return
     * @see
     * @return List<User>
     * @author lizl
     */
    public List<User> getObjListByIdS(String userIdsTemp)
    {
        List<User> tmepUserList = new ArrayList<User>();
        String[] userIds = userIdsTemp.split(",");
        User temp = null;
        try
        {
            for (String userID : userIds)
            {
                userID = userID.trim();
                if (userID.length() > 0)
                {
                    temp = new User();
                    temp.setUserId(Long.valueOf(userID));
                    user = userService.getUserById(temp);
                    tmepUserList.add(user);
                }
            }
        }
        catch (SHException e)
        {
            //  LOGGER.error(e.getMessage());
        }
        return tmepUserList;
    }
    
    /**
     * Description: 跳转到修改用户密码界面<br>
     * Implement: <br>
     * @return
     * @see
     * @return String
     * @author Administrator
     */
    public String toChangeUserPwd()
    {
        //...
        return "toChange";
    }
    
    /**
     * Description: 修改密码<br>
     * Implement: <br>
     * @return
     * @see
     * @return String
     * @author Administrator
     */
    public String changeUserPwd()
    {
        try
        {
            initService();
            String userPwd = user.getUserPwd();
            /*HashMap paramMap = new LinkedHashMap<String, Object>();
            paramMap.put("userName", user.getUserName());*/
            user = userService.getUser(user);
            user.setUserPwd(userPwd);
            userService.modUser(user);
        }
        catch (SHException e)
        {
            //  LOGGER.error(e.getMessage());
        }
        return SUCCESS;
    }
    
    /**
     * 
     * Description: 获取某文件的路径<br>
     * Implement: <br>
     * @return
     * @see
     * @return String
     * @author Administrator
     */
    public String getPath()
    {
        
        HttpServletRequest request = ServletActionContext.getRequest();	
        
        // 获取图片的存放路径    File.separator避免不同的操作系统之间的差异
        String destPath = request.getSession()
                .getServletContext()
                .getRealPath("charts");
        
        return destPath;
    }
    
    /**
     * Description: 字符乱码转换<br>
     * Implement: <br>
     * @param str
     * @return
     * @throws UnsupportedEncodingException
     * @see
     * @return String
     * @author Administrator
     */
    /*private String changeToUTF8(String str) throws UnsupportedEncodingException
    {
        String encoding = this.getRequest().getCharacterEncoding();
        String temp = new String(str.getBytes(encoding), "UTF-8");
        return temp;
    }*/

    /**
     * Description: 属性验证是否已经存在：用户名<br>
     * Implement: <br>
     * @return
     * @see
     * @return String
     * @author Administrator
     */
    public String verifyUserNameUnique()
    {
        HttpServletRequest req = getRequest();
        HttpServletResponse res = getResponse();
        String validateId = req.getParameter("validateId");
        String validateValue = req.getParameter("validateValue");
        String validateError = req.getParameter("validateError");
        
        try
        {
            initService();
            JSONArray jsonValidateReturn = new JSONArray();
            jsonValidateReturn.add(validateId);
            jsonValidateReturn.add(validateError);
            if (StringUtils.isNotEmpty(validateValue))
            {
                User obj = new User();
                obj.setUserName(validateValue);
                obj = userService.getUser(obj);
                if (GeneralUtils.isNotNull(obj))
                {
                    jsonValidateReturn.add("false");
                }
                else
                {
                    jsonValidateReturn.add("true");
                }
                res.setContentType("text/html;charset=utf-8");
                res.getWriter().write(jsonValidateReturn.toString());
            }
        }
        catch (Throwable e)
        {
            LOGGER.error(e.getMessage());
        }
        return null;
    }
    
    /**
     * Description: 属性验证是否已经存在：用户电话号码<br>
     * Implement: <br>
     * @return
     * @see
     * @return String
     * @author Administrator
     */
    public String verifyUserMobileUnique()
    {
        HttpServletRequest req = getRequest();
        HttpServletResponse res = getResponse();
        String validateId = req.getParameter("validateId");
        String validateValue = req.getParameter("validateValue");
        String validateError = req.getParameter("validateError");
        
        try
        {
            initService();
            JSONArray jsonValidateReturn = new JSONArray();
            jsonValidateReturn.add(validateId);
            jsonValidateReturn.add(validateError);
            if (StringUtils.isNotEmpty(validateValue))
            {
                User obj = new User();
                obj.setUserMobile(validateValue);
                obj = userService.getUser(obj);
                if (GeneralUtils.isNotNull(obj))
                {
                    jsonValidateReturn.add("false");
                }
                else
                {
                    jsonValidateReturn.add("true");
                }
                res.setContentType("text/html;charset=utf-8");
                res.getWriter().write(jsonValidateReturn.toString());
            }
        }
        catch (Throwable e)
        {
            LOGGER.error(e.getMessage());
        }
        return null;
    }
    
    /**
     * Description: 属性验证是否已经存在：身份证ID<br>
     * Implement: <br>
     * @return
     * @see
     * @return String
     * @author Administrator
     */
    public String verifyUserIdentityCardUnique()
    {
        HttpServletRequest req = getRequest();
        HttpServletResponse res = getResponse();
        String validateId = req.getParameter("validateId");
        String validateValue = req.getParameter("validateValue");
        String validateError = req.getParameter("validateError");
        
        try
        {
            initService();
            JSONArray jsonValidateReturn = new JSONArray();
            jsonValidateReturn.add(validateId);
            jsonValidateReturn.add(validateError);
            if (StringUtils.isNotEmpty(validateValue))
            {
                User obj = new User();
                obj.setUserIdentityCard(validateValue);
                obj = userService.getUser(obj);
                if (GeneralUtils.isNotNull(obj))
                {
                    jsonValidateReturn.add("false");
                }
                else
                {
                    jsonValidateReturn.add("true");
                }
                res.setContentType("text/html;charset=utf-8");
                res.getWriter().write(jsonValidateReturn.toString());
            }
        }
        catch (Throwable e)
        {
            LOGGER.error(e.getMessage());
        }
        return null;
    }
    
    /**
     * Description: 初始化查询条件<br>
     * Implement: <br>
     * @param user：封装对象
     * @param searchName：查询类型
     * @param searchValue：查询值
     * @return
     * @see
     * @return User
     * @author Administrator
     */
    private User initSearch(User user, String searchName,String searchValue)
    {
        if(searchName != null){
            if (StringUtils.equals("userName", searchName))
            {
                user.setUserName(searchValue);
            }
            else if (StringUtils.equals("userMobile", searchName))
            {
                user.setUserMobile(searchValue);
            }
        }
        return user;
    }
    
    public IUserService getUserService()
    {
        return userService;
    }
    
    public void setUserService(IUserService userService)
    {
        this.userService = userService;
    }
    
    public User getUser()
    {
        return user;
    }
    
    public void setUser(User user)
    {
        //....
        
        this.user = user;
    }
    
    public List<User> getUserList()
    {
        return userList;
    }
    
    public void setUserList(List<User> userList)
    {
        this.userList = userList;
    }
    
    public String getUserIds()
    {
        return userIds;
    }
    
    public void setUserIds(String userIds)
    {
        this.userIds = userIds;
    }
    
    public String getSearchName()
    {
        return searchName;
    }
    
    public void setSearchName(String searchName)
    {
        this.searchName = searchName;
    }
    
    public String getSearchValue()
    {
        return searchValue;
    }
    
    public void setSearchValue(String searchValue)
    {
        this.searchValue = searchValue;
    }
    
    /*private String testFusionCharts(){
        return this.month;
    }*/

}
